from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet

from .models import Host
from .serializers import HostSerializer
from ping3 import ping


class CityViewSet(ModelViewSet):
    from .models import City
    from .serializers import CitySerializer
    queryset = City.objects.all()
    serializer_class = CitySerializer


class RoomViewSet(ModelViewSet):
    from .models import Room
    from .serializers import RoomSerializer
    queryset = Room.objects.all()
    serializer_class = RoomSerializer



class HostViewSet(ModelViewSet):
    from .models import Host
    from .serializers import HostSerializer
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    @action(detail=True, methods=['get'])
    def ping(self, request, pk=None):
        host = self.get_object()
        is_reachable = ping(host.ip_address, timeout=2) is not None
        host.is_alive = is_reachable
        host.save()
        return Response({'reachable': is_reachable})

    @action(detail=True, methods=['post'])
    def change_password(self, request, pk=None):
        host = self.get_object()
        new_password = host.change_password()
        return Response({
            'message': 'Password changed successfully',
            'new_password': new_password
        }, status=status.HTTP_200_OK)


class PasswordChangeLogViewSet(viewsets.ReadOnlyModelViewSet):
    from .models import PasswordChangeLog
    from .serializers import PasswordChangeLogSerializer
    queryset = PasswordChangeLog.objects.all()
    serializer_class = PasswordChangeLogSerializer


class HostCountStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    from .models import HostCountStatistics
    from .serializers import HostCountStatisticsSerializer
    queryset = HostCountStatistics.objects.all()
    serializer_class = HostCountStatisticsSerializer